<template>
  <div>
    <!-- 条件搜索表单： 品牌和分类的下拉选框  -->
    <div style="background:#fff;padding:20px">
      <el-form :inline="true">
        <el-form-item label="品牌">
          <el-select
            v-model="searchObj.brandId"
            placeholder="请选择品牌"
            style="width: 340px"
          >
            <el-option
              v-for="item in brands"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分类">
          <el-cascader :props="props" v-model="searchObj.categoryId" />
        </el-form-item>
      </el-form>
      <el-button type="primary" size="small" @click="handleSearch">
        搜索
      </el-button>
      <el-button size="small" @click="handleReset">重置</el-button>
    </div>
    <div>
      <el-button size="small" type="success" @click="handleShowSaveDialog">
        添加
      </el-button>
    </div>
    <!-- 用户分页列表表格 -->
    <div>
      <el-table :data="categoryBrands" stripe style="width: 100%">
        <el-table-column prop="categoryName" label="分类" width="100" />
        <el-table-column prop="brandName" label="品牌" width="100" />
        <el-table-column prop="brandLogo" label="品牌图标" #default="scope">
          <img
            :src="scope.row.brandLogo"
            alt=""
            style="width:40px;height:40px;"
          />
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="220">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">
              修改
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top:20px;text-align:center">
        <el-pagination
          v-model:current-page="pageNum"
          v-model:page-size="pageSize"
          :page-sizes="[1, 2, 3, 4, 5]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="initPageData"
          @current-change="initPageData"
        />
      </div>
    </div>

    <!-- 新增/修改品牌的对话框 -->
    <div>
      <el-dialog v-model="dialogFormVisible" title="添加或修改">
        <el-form :model="categoryBrand">
          <el-form-item label="品牌">
            <el-select
              v-model="categoryBrand.brandId"
              placeholder="请选择品牌"
              style="width: 340px"
            >
              <el-option
                v-for="item in brands"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="分类">
            <el-cascader :props="props" v-model="categoryBrand.categoryId" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSaveOrUpdateCategoryBrand">
              提交
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script setup>
import { onMounted, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { GetAllBrands } from '@/api/brand'
import { GetCategoriesByPid } from '@/api/category'
import {
  GetCategoryBrands,
  GetCategoryBrandById,
  UpdateCategoryBrand,
  DeleteCategoryBrand,
  SaveCategoryBrand,
} from '@/api/categoryBrand'
//修改按钮事件函数：查询数据回显弹出对话框
const handleEdit = async row => {
  const { data } = await GetCategoryBrandById(row.id)
  categoryBrand.value = data.item
  dialogFormVisible.value = true
}

//对话框属性和函数
const categoryBrand = ref({})
const dialogFormVisible = ref(false)
const handleSaveOrUpdateCategoryBrand = () => {
  if (categoryBrand.value.id) {
    //更新
    handleUpdate()
  } else {
    //新增
    handleSave()
  }
}
const handleSave = async () => {
  if (
    categoryBrand.value.categoryId &&
    categoryBrand.value.categoryId.length === 3
  ) {
    categoryBrand.value.categoryId = categoryBrand.value.categoryId[2]
  }
  await SaveCategoryBrand(categoryBrand.value)
  ElMessage.success('新增成功')
  dialogFormVisible.value = false
  initPageData()
}
const handleUpdate = async () => {
  if (
    categoryBrand.value.categoryId &&
    categoryBrand.value.categoryId.length === 3
  ) {
    categoryBrand.value.categoryId = categoryBrand.value.categoryId[2]
  }
  await UpdateCategoryBrand(categoryBrand.value)
  ElMessage.success('更新成功')
  dialogFormVisible.value = false
  initPageData()
}
//添加按钮事件函数：弹出新增对话框
const handleShowSaveDialog = () => {
  categoryBrand.value = {}
  dialogFormVisible.value = true
}

//删除按钮事件函数
const handleDelete = row => {
  DeleteCategoryBrand(row.id).then(r => {
    ElMessage.success('删除成功')
    initPageData()
  })
}

//搜索和重置按钮事件函数
const handleSearch = () => {
  //   console.log(searchObj.value)
  //searchObj搜集的分类id是选择的所有分类的id,已经使用三级分类id提交查询
  if (searchObj.value.categoryId && searchObj.value.categoryId.length === 3) {
    searchObj.value.categoryId = searchObj.value.categoryId[2]
  }
  initPageData()
}

const handleReset = () => {
  searchObj.value = {}
  pageNum.value = 1
  pageSize.value = 3
  initPageData()
}

//分类级联选择器需要的属性函数
const props = {
  lazy: true,
  label: 'name', //配置级联选择器使用数据中的哪个属性当做标题展示
  value: 'id', //配置级联选择器使用数据中的哪个属性当做选中的值
  leaf: 'leaf', //配置级联选择器使用数据中的哪个属性判断节点是否有下一级
  async lazyLoad(node, resolve) {
    //页面渲染时默认会执行一次懒加载方法
    console.log(node, '1111')
    let pid = 0
    if (node.level != 0) {
      pid = node.data.id
    }
    //查询1级分类集合
    const { data: data3 } = await GetCategoriesByPid(pid)
    categories.value = data3.items
    categories.value.forEach(c => {
      c.leaf = !c.hasChildren
    })
    resolve(categories.value)
  },
}

const pageNum = ref(1)
const pageSize = ref(3)
const searchObj = ref({})
const total = ref(0)
const categoryBrands = ref([])
const categories = ref([])
const brands = ref([])
const initPageData = async () => {
  //查询分类品牌数据
  const { data } = await GetCategoryBrands(
    pageNum.value,
    pageSize.value,
    searchObj.value
  )
  categoryBrands.value = data.page.list
  total.value = data.page.total
  //查询所有品牌
  const { data: data2 } = await GetAllBrands()
  brands.value = data2.items
}

onMounted(() => {
  initPageData()
})
</script>
